package server;

import java.io.IOException;
import java.io.InputStream;

/**
 * @description: 请求信息封装类
 * @author: Archie Wan
 * @time: 2020/12/27 13:51
 */
public class Request {

    private String method; // 请求方式-[GET/POST]
    private String url; // 资源定位
    private InputStream inputStream; // 输入流
    private String host; // 主机
    private Integer port; // 端口
    
    public String getMethod() {
        return method;
    }
    public void setMethod(String method) {
        this.method = method;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public InputStream getInputStream() {
        return inputStream;
    }
    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }
    public String getHost() {
        return host;
    }
    public void setHost(String host) {
        this.host = host;
    }
    public Integer getPort() {
        return port;
    }
    public void setPort(Integer port) {
        this.port = port;
    }
    
    public Request() {}
    
    public Request(InputStream inputStream) throws IOException {
        this.inputStream = inputStream;
    
        /* 以下 while 针对网络间断进行判定，没有数据则一直读 */
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }
        byte[] bytes = new byte[count];
        inputStream.read(bytes);
    
        String inputStr = new String(bytes);
        // 获取首行请求头信息
        String firstStr = inputStr.split("\\n")[0];
        String[] s = firstStr.split(" ");
        this.method = s[0];
        this.url = s[1];
        
    
        String hostPort = inputStr.split("\\r\\n")[1].split(" ")[1];
        this.host = hostPort.split(":")[0];
        String port = hostPort.split(":")[1];
        if (port == null || port.isEmpty()) {
            this.port = 80;
        } else {
            this.port = Integer.parseInt(port);
        }
    
        System.out.println("===> url = " + this.url);
        System.out.println("===> method = " + this.method);
        System.out.println("===> host = " + this.host);
        System.out.println("===> port = " + this.port);
    }
}
